package cn.wonhigh.o2o.openfire.plugins.intercepter;

import java.util.HashMap;
import java.util.Map;

import org.dom4j.Element;
import org.jivesoftware.openfire.interceptor.PacketInterceptor;
import org.jivesoftware.openfire.interceptor.PacketRejectedException;
import org.jivesoftware.openfire.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;

import cn.wonhigh.o2o.openfire.plugins.util.HttpUtil;

import com.alibaba.fastjson.JSON;

public class MessageTransmitInterceptor implements PacketInterceptor {

	private static final Logger LOG = LoggerFactory
			.getLogger(MessageTransmitInterceptor.class);

	private String transmitURL = null;

	public MessageTransmitInterceptor(String transmitURL) {
		this.transmitURL = transmitURL;
	}

	@Override
	public void interceptPacket(Packet packet, Session session,
			boolean incoming, boolean processed) throws PacketRejectedException {
		if (!incoming || processed || null == packet) {
			return;
		}
		if (packet instanceof Message) {
			// 微信收消息
			Message message = (Message) packet;
			String body = message.getBody();
			if (message.getType() == Message.Type.chat && body != null) {
				try {
					String to = message.getTo().getNode();
					String from = message.getFrom().getNode();
					LOG.info("接收消息内容 ==> " + message.toXML());
					if(!body.startsWith("{\"")){ // 不是想要的json数据
						return;
					}
					
					@SuppressWarnings("unchecked")
					Map<String, String> msg = JSON.parseObject(body, Map.class);
					if(null == msg){
						return;
					}
					
					if (msg != null && "null".equals(msg.get("downloadUrl"))) {
						throw new PacketRejectedException();
					}
					// 百通发送给微信:微信帐号是appid长一些，百通的帐号比较短，暂时只有这个办法区分。
					if (to.length() > 20 && from.length() < 20) {
						Element receiptElement = message.getChildElement("received", "urn:xmpp:receipts");
						if (receiptElement != null) { 
							// 回执消息由OfflineMsgPlugin处理。
							return;
						}
						Map<String, String> params = new HashMap<String, String>();
						params.put("to", to);
						params.put("from", from);
						params.put("msg", message.getBody());
						HttpUtil.httpPost(transmitURL, params);
						throw new PacketRejectedException();
					}
				} catch (Exception e) {
					// 阻止包进一步处理
					if (e instanceof PacketRejectedException) {
						throw e;
					}
					LOG.error(e.getMessage(), e);
				}
			}
		}
	}
}
